package com.skt.controller;

import com.skt.domain.DTO.request.MerchantOrderQueryRequest;
import com.skt.domain.VO.RentalOrderVO;
import com.skt.exception.BusinessException;
import com.skt.exception.OrderErrorCode;
import com.skt.exception.OrderException;
import com.skt.result.PageResult;
import com.skt.service.MerchantOrderService;
import com.skt.utils.LogUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

@RestController
@RequestMapping("/merchant/orders")
@RequiredArgsConstructor
@Tag(name = "商家订单管理接口", description = "商家查询其名下租赁订单相关操作")
public class MerchantOrderController {

    private final MerchantOrderService merchantOrderService;

    @Operation(
            summary = "查询商家订单列表",
            description = "获取当前登录商家的租赁订单列表，支持按订单状态、租赁时间范围、分页等条件查询。仅限商家本人访问。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "成功返回订单分页列表"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "401", description = "未授权访问，用户未登录或token失效"),
            @ApiResponse(responseCode = "403", description = "权限不足，非商家角色或尝试访问他人数据"),
            @ApiResponse(responseCode = "500", description = "服务器内部处理错误")
    })
    @GetMapping
    public ResponseEntity<PageResult<RentalOrderVO>> listMerchantOrders(
            @Parameter(description = "商家订单查询条件", required = true)
            @Valid MerchantOrderQueryRequest queryRequest) {

        LogUtil.setTraceId();
        LogUtil.startTimer("MERCHANT_ORDER_LIST");

        try {
            PageResult<RentalOrderVO> result = merchantOrderService.MerchantOrderQueryRequest(queryRequest);
            return ResponseEntity.ok(result);
        } catch (BusinessException e) {
            LogUtil.error("MERCHANT_ORDER", "LIST", "查询商家订单列表业务异常", e);
            throw e;
        } catch (Exception e) {
            LogUtil.error("MERCHANT_ORDER", "LIST", "查询商家订单列表系统异常", e);
            throw OrderException.of(OrderErrorCode.QUERY_ORDER_LIST_FAILED, "查询商家订单列表失败");
        } finally {
            LogUtil.stopTimer();
            LogUtil.clearContext();
        }
    }


    @Operation(
            summary = "确认发货",
            description = "商家对指定租赁订单执行发货操作。仅当订单状态为“已支付”（状态码2）时允许发货。操作后订单状态将更新为“已发货”（状态码3）。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "发货成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误，如订单ID无效"),
            @ApiResponse(responseCode = "401", description = "未授权访问，用户未登录或token失效"),
            @ApiResponse(responseCode = "403", description = "权限不足，非该订单所属商家，或订单不属于当前用户"),
            @ApiResponse(responseCode = "409", description = "订单状态不允许发货（如未支付、已取消等）"),
            @ApiResponse(responseCode = "404", description = "订单不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部处理错误")
    })
    @PutMapping("/{id}/ship")
    public ResponseEntity<Void> shipOrder(
            @Parameter(description = "订单ID", required = true, example = "12345")
            @PathVariable("id")
            @NotNull(message = "订单ID不能为空")
            Long id) {

        LogUtil.setTraceId();
        LogUtil.startTimer("MERCHANT_ORDER_SHIP");

        try {
            merchantOrderService.shipOrder(id);
            return ResponseEntity.ok().build();
        } catch (BusinessException e) {
            LogUtil.error("MERCHANT_ORDER", "SHIP", "发货业务异常 - 订单ID: " + id, e);
            throw e;
        } catch (Exception e) {
            LogUtil.error("MERCHANT_ORDER", "SHIP", "发货系统异常 - 订单ID: " + id, e);
            throw OrderException.of(OrderErrorCode.SHIP_ORDER_FAILED, "订单发货失败");
        } finally {
            LogUtil.stopTimer();
            LogUtil.clearContext();
        }
    }


    @Operation(
            summary = "确认归还",
            description = "商家对指定租赁订单执行确认归还操作。仅当订单状态为“已取货”（状态码4）时允许操作。操作后订单状态将更新为“已归还”（状态码5）。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "确认归还成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误，如订单ID无效"),
            @ApiResponse(responseCode = "401", description = "未授权访问，用户未登录或token失效"),
            @ApiResponse(responseCode = "403", description = "权限不足，非该订单所属商家"),
            @ApiResponse(responseCode = "404", description = "订单不存在"),
            @ApiResponse(responseCode = "409", description = "订单状态不允许确认归还（如未取货、已归还等）"),
            @ApiResponse(responseCode = "500", description = "服务器内部处理错误")
    })
    @PutMapping("/{id}/return")
    public ResponseEntity<Void> returnOrder(
            @Parameter(description = "订单ID", required = true, example = "12345")
            @PathVariable("id")
            @NotNull(message = "订单ID不能为空")
            Long id) {

        LogUtil.setTraceId();
        LogUtil.startTimer("MERCHANT_ORDER_RETURN");

        try {
            merchantOrderService.returnOrder(id);
            return ResponseEntity.ok().build();
        } catch (BusinessException e) {
            LogUtil.error("MERCHANT_ORDER", "RETURN", "确认归还业务异常 - 订单ID: " + id, e);
            throw e;
        } catch (Exception e) {
            LogUtil.error("MERCHANT_ORDER", "RETURN", "确认归还系统异常 - 订单ID: " + id, e);
            throw OrderException.of(OrderErrorCode.RETURN_ORDER_FAILED, "订单确认归还失败");
        } finally {
            LogUtil.stopTimer();
            LogUtil.clearContext();
        }
    }
}